package com.shipwe.loans.ui.presenter

import com.shipwe.loans.http.ApiService
import com.shipwe.loans.http.ApiService.addCommonParams
import com.shipwe.loans.http.IHttpCallback
import com.shipwe.loans.pro.ShipwePresenter
import com.shipwe.loans.ui.view.IUserPointsView
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/15 16:26
 * @Annotation：积分明细列表 Presenter 实现
 */
class UserPointsPresenter(private val iView: IUserPointsView) : ShipwePresenter(iView) {

    /**
     * 获取积分明细列表
     */
    fun loadUserPointsListAction(){
        val httpUrl = ApiService.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.SHIPWE_API_COUPON_LIST_PATH)
            put("mobile", ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_MOBILE))
            put("infoType","scoreHistory")
            put("page",iView.getPointsPage())
            put("size","20")
        }
        doHttpPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                iView.dismissShipweLoading()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null){
                            val pointsArray = obj.optJSONArray("userScoreLogList")
                            val pointsList = arrayListOf<JSONObject>()
                            if (pointsArray != null) {
                                for (i in 0..<pointsArray.length()){
                                    pointsList.add(pointsArray.optJSONObject(i))
                                }
                            }
                            val totalCount = obj.optInt("userScoreLogSize")
                            iView.showUserPointsList(totalCount,pointsList)
                        }
                    }
                    else -> {
                        iView.showShipweToast(data.optString("msg"))
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                val pointsList = arrayListOf<JSONObject>()
                iView.showUserPointsList(0,pointsList)
            }
            override fun onRequestFinish() {
                iView.dismissShipweLoading()
            }
        })
    }
}